package com.apes.enquiry.product.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.product.model.ReplacementProduct;
import com.apes.enquiry.product.repository.ProductDao;
import com.apes.enquiry.product.repository.ReplacementProductRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MD5Util;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class ReplacementProductService extends DomainService {

    @Autowired
    private ReplacementProductRepository replacementProductRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Autowired
    private ProductDao productDao;


    /**
     * 动态条件查询
     * @param request
     * @return
     */
    public List<ReplacementProduct> conditionQuery(SimpleRequest request){
        JSONObject jo = request.getJO();
        User user = userRepository.findOne(Integer.valueOf(request.getSession().getUserId()));
        PartyRole supplier = partyRoleRepository.findOne(user.getPerson().getId());
        return replacementProductRepository.findAll(JpaDsl.toCriteriaIgnoreNull("replacement", "EQ", jo.getString("replacement"),
                "pn", "EQ", jo.getString("pn"),
                "brand", "EQ", jo.getString("brand"),
                "supplier", "EQ", supplier
        ));

    }

    /**
     * 批量删除
     * @param request
     * @return
     */
    public List<ReplacementProduct> delReplacement(SimpleRequest request){
        List<ReplacementProduct> replacementProducts = request.getA("del", ReplacementProduct.class);
        replacementProducts.forEach(replacement -> {
            if (Objects.nonNull(replacement.getId())){
                replacementProductRepository.delete(replacement);
            }
        });
        return conditionQuery(request);
    }


    /**
     * 替换件关系上传
     * @param request
     * @return
     */
    public JSONObject importReplacementProduct(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray titleColumnArray = new JSONArray();
        User user = userRepository.findOne(Integer.parseInt(request.getSession().getUserId()));
        String key = appendImportReturn_New(importData, titleColumnArray,user);
        JSONObject returnData = new JSONObject();
        returnData.put(key, titleColumnArray);
        return returnData;
    }

    /**
     * 并行流导入
     * @param importData
     * @param titleColumnArray
     * @return
     */
    private String appendImportReturn_New(JSONObject importData, JSONArray titleColumnArray,User user) {

        AtomicReference<String> key = new AtomicReference<>();

        JSONArray titleArray = new JSONArray(3);
        titleArray.add("替换件组号");
        titleArray.add("原厂零件号");
        titleArray.add("车品牌");
        titleColumnArray.add(titleArray);
        List<ReplacementProduct> replacementList =Collections.synchronizedList(new ArrayList());
        importData.forEach((k, v) -> {
            key.set(k);
            JSONArray importDataValueArray = (JSONArray) v;
            importDataValueArray.parallelStream().forEach( item -> {
                ReplacementProduct replacementProduct = new ReplacementProduct();
                JSONArray iValueArray = (JSONArray) item;
                if (iValueArray.size() <3) return;
                String replacement = "";
                String pn = "";
                String brand = "";

                for (int i = 0; i < iValueArray.size(); i++) {
                    if (Objects.isNull(iValueArray.get(i))) continue;
                    switch (i) {
                        case 0:
                            replacement = iValueArray.getString(0);
                            break;
                        case 1:
                            pn = iValueArray.getString(1);
                            break;
                        case 2:
                            brand = iValueArray.getString(2);
                            break;
                    }
                }
                if ("替换件组号".equals(replacement) || "原厂零件号".equals(pn)) {    // 匹配中英文
                    return;
                }
                replacementProduct.setReplacement(replacement);
                replacementProduct.setPn(pn);
                replacementProduct.setBrand(brand);
                replacementProduct.setSupplier(user.getPerson());
                replacementList.add(replacementProduct);
            });
        });
        if(replacementList.size()>0){
            String is = null;
            String id=null;
            Map<String,List<ReplacementProduct>> map = replacementList.stream().collect(Collectors.groupingBy(ReplacementProduct ::getReplacement));
            List<ReplacementProduct> list = Collections.synchronizedList(new ArrayList());
            for(List<ReplacementProduct> replacements : map.values()){
                for(ReplacementProduct replacement : replacements ){
                    if(id==null || !replacement.getReplacement().equals(is)){
                        is=replacement.getReplacement();
                        id = MD5Util.encrypt(Calendar.getInstance().getTimeInMillis()+replacement.getPn()).substring(0,8);
                    }
                    replacement.setReplacement(id);
                    list.add(replacement);
                }
            }
            productDao.replacementInsert(list);
        }
        return key.get();
    }



}
